<template>
	<el-drawer
		v-model="drawerVisible"
		@closed="resetForm(ruleFormRef)"
		:destroy-on-close="true"
		size="50%"
		:close-on-click-modal="false"
		:title="`${drawerProps.title}赛事`"
	>
		<el-form
			ref="ruleFormRef"
			:model="ruleForm"
			:rules="rules"
			label-width="180px"
			label-position="left"
			class="demo-ruleForm"
			status-icon
		>
			<div class="title">
				<span>基本信息</span>
			</div>
			<el-form-item label="所属商户：" v-if="!globalStore.isPlatform" prop="merchants">
				<el-select v-model="ruleForm.merchants" placeholder="请选择">
					<el-option v-for="item in MerchantsList" :key="item?.MerchantId" :label="item?.companyName" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="赛事名称：" prop="name">
				<el-input :maxlength="50" placeholder="请输入" v-model="ruleForm.name" />
			</el-form-item>
			<el-form-item label="赛事封面图：" prop="coverPicture">
				<UploadImg v-model:image-url="ruleForm.coverPicture">
					<template #tip>
						<div class="el-upload__tip">支持格式：.jpg .png，文件大小不能超过500kb，建议尺寸：375*80</div>
					</template>
				</UploadImg>
			</el-form-item>
			<el-form-item label="详情轮播图：" prop="fileList">
				<UploadImgs v-model:file-list="ruleForm.fileList">
					<template #tip>
						<div class="el-upload__tip">支持格式：.jpg .png，文件大小不能超过500kb，建议尺寸：375*80</div>
					</template>
				</UploadImgs>
			</el-form-item>
			<el-form-item label="赛事举办城市：" prop="city">
				<CitySelctComp v-model:city="ruleForm.city" @update:city="handleCityClick" />
			</el-form-item>
			<el-form-item label="比赛地点：" prop="address">
				<el-input :maxlength="50" placeholder="请输入" v-model="ruleForm.address" />
			</el-form-item>
			<el-form-item label="赛事举办详细地址：" prop="detailsAddress">
				<el-input @focus="showMap" placeholder="请点击选择" v-model="ruleForm.detailsAddress" />
			</el-form-item>
			<el-form-item label="赛事报名时间：" prop="signUpBeginTime">
				<el-date-picker
					v-model="timeManagement.signTime"
					type="daterange"
					value-format="YYYY-MM-DD"
					:disabledDate="pickerOptions"
					range-separator="~"
					start-placeholder="开始时间"
					end-placeholder="结束时间"
					size="large"
				/>
			</el-form-item>
			<el-form-item label="赛事比赛时间：" prop="matchBeginTime">
				<el-date-picker
					v-model="timeManagement.gameTime"
					type="daterange"
					value-format="YYYY-MM-DD"
					range-separator="~"
					start-placeholder="开始时间"
					:disabledDate="disablesDate"
					end-placeholder="结束时间"
					size="large"
				/>
			</el-form-item>
			<el-form-item label="赛事咨询人：" prop="consultant">
				<el-input :maxlength="50" placeholder="请输入" v-model="ruleForm.consultant" type="text" />
			</el-form-item>
			<el-form-item label="赛事咨询电话：" prop="telePhone">
				<el-input
					:maxlength="13"
					placeholder="请输入电话号码，座机请添加区号如：“010-xxxxxxxx”"
					v-model="ruleForm.telePhone"
					type="text"
				/>
			</el-form-item>
			<el-form-item label="赛事性质：" prop="telePhone">
				<el-radio-group v-model="ruleForm.officialOrBusiness">
					<el-radio :label="0">官方</el-radio>
					<el-radio :label="1">商业</el-radio>
				</el-radio-group>
			</el-form-item>
			<div class="title">
				<span>收费规则</span>
			</div>
			<el-form-item>
				<el-radio-group @change="handleChargeTypeChange" v-model="ruleForm.chargeType">
					<div class="radioBox">
						<el-radio :label="1">按比赛项目收费</el-radio>
					</div>
					<div class="radioBox">
						<el-radio :label="2">按赛事收费</el-radio>
						<el-input
							:disabled="ruleForm.chargeType == 1"
							placeholder="请输入"
							maxlength="10"
							v-model="ruleForm.money"
							size="small"
							type="text"
						>
							<template #append>
								<span>元/人</span>
							</template>
						</el-input>
					</div>
				</el-radio-group>
			</el-form-item>
			<div style="margin-left: 180px; color: #999999">按赛事收费：即参赛者交设定费用可报名所有项目，不再额外收费</div>
			<div class="title">
				<span>举办单位</span>
			</div>
			<Card title="主办单位" type="hostUnit" v-model:data="ruleForm.hostUnit" />
			<Card title="承办单位" type="undertakeUnit" v-model:data="ruleForm.undertakeUnit" />
			<Card title="协办单位" type="assistingUnit" v-model:data="ruleForm.assistingUnit" />
			<div class="title">
				<span>赛事详情</span>
			</div>
			<WangEditor v-model:value="ruleForm.details" />
			<div class="title">
				<span>赛事须知</span>
			</div>
			<el-input v-model="ruleForm.instructions" placeholder="请输入" type="textarea" />
			<el-form-item label="赛事状态：">
				<el-radio-group v-model="ruleForm.isEnable">
					<el-radio :label="1">启用</el-radio>
					<el-radio :label="0">禁用</el-radio>
				</el-radio-group>
			</el-form-item>
		</el-form>
		<BaiduMapSelectVue :longitude="lng" :latitude="lat" ref="bmapAddressSelect" @confirm-map-address="confirmMapAddress">
		</BaiduMapSelectVue>
		<template #footer>
			<el-button @click="resetForm(ruleFormRef)">取消</el-button>
			<el-button type="primary" @click="handleSubmit(1)">保存</el-button>
			<el-button type="success" v-show="!drawerProps.isView" @click="handleSubmit(2)">保存并发布</el-button>
		</template>
	</el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive, nextTick, watch } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import Card from "@/views/competition/event/components/Card.vue";
import WangEditor from "@/components/MyWangEditor/index.vue";
import BaiduMapSelectVue from "@/components/BaiduMapSelect/index.vue";
import CitySelctComp from "@/components/CitySelectCom/index.vue";
import companyInfoApi from "@/api/modules/paymentOrderInfo";
import competitionApi from "@/api/modules/competition";
import UploadImgs from "@/components/Upload/Imgs.vue";
import UploadImg from "@/components/Upload/Img.vue";
import type { UploadUserFile } from "element-plus";
import { ruleForm, TimeManag } from "../interface";
import { GlobalStore } from "@/stores";
const globalStore = GlobalStore();
const timeManagement = reactive<TimeManag>({
	signTime: [],
	gameTime: []
});
const bmapAddressSelect = ref(); //百度地图组件实例
const lng = ref<number>(-1);
const lat = ref<number>(-1);
// 表单信息
const ruleForm = ref<ruleForm>({
	id: null,
	name: "",
	merchants: "",
	coverPicture: "",
	rotationPicture: "",
	fileList: [],
	city: "",
	address: "",
	detailsAddress: "",
	point: "",
	signUpBeginTime: "",
	singUpEndTime: "",
	matchBeginTime: "",
	matchEndTime: "",
	consultant: "",
	telePhone: "",
	state: 1,
	isEnable: 1,
	details: "",
	instructions: "",
	chargeType: 1,
	money: 0,
	officialOrBusiness: 0,
	hostUnit: [
		{
			name: "",
			logoUrl: "",
			responsible: "",
			telePohone: ""
		}
	],
	undertakeUnit: [
		{
			name: "",
			logoUrl: "",
			responsible: "",
			telePohone: ""
		}
	],
	assistingUnit: [
		{
			name: "",
			logoUrl: "",
			responsible: "",
			telePohone: ""
		}
	]
});
// 表单规则
const rules = reactive<FormRules>({
	name: [{ required: true, message: "赛事名称不能为空！", trigger: "blur" }],
	merchants: [{ required: true, message: "请选择所属商户！", trigger: "change" }],
	coverPicture: [{ required: true, message: "赛事封面图为必填项！", trigger: "change" }],
	fileList: [{ required: true, message: "详情轮播图为必填项", trigger: "change" }],
	city: [{ required: true, message: "请选择举办城市！", trigger: "change" }],
	address: [{ required: true, message: "比赛地点不能为空！", trigger: "blur" }],
	detailsAddress: [{ required: true, message: "请选择赛事举办详细地址！", trigger: "change" }],
	signUpBeginTime: [{ required: true, message: "请选择报名时间！", trigger: "change" }],
	matchBeginTime: [{ required: true, message: "请选择比赛时间！", trigger: "change" }],
	consultant: [{ required: true, message: "赛事咨询人不能为空！", trigger: "blur" }],
	telePhone: [
		{ required: true, message: "赛事咨询电话不能为空！", trigger: "blur" },
		{
			pattern: /^(1[3-9]\d{9}|0[1-9]\d{1,2}-[2-8]\d{6,7}(-\d{1,4})?)$/,
			message: "电话号码格式不正确"
		}
	],
	officialOrBusiness: [{ required: true, message: "请选择赛事性质！", trigger: "change" }],
	logoUrl: [{ required: true, message: "单位Logo不能为空！", trigger: "change" }]
});
// 获取商户列表
const MerchantsList = ref<Array<any>>();
const getCompanyTypeList = async () => {
	let { result } = await companyInfoApi.GetCompanysList();
	let { data } = result as any;
	MerchantsList.value = data;
};
// 如果是编辑就获取一下详情
const getDetailApi = () => {
	nextTick(async () => {
		if (!drawerProps.value.row?.id) return;
		let res = await competitionApi.GetCompetitionDetailsByIdApi(drawerProps.value.row.id);
		let { data } = res.result;
		ruleForm.value = data;
		timeManagement.gameTime = [data.matchBeginTime, data.matchEndTime];
		timeManagement.signTime = [data.signUpBeginTime, data.singUpEndTime];
		ruleForm.value.fileList = data.rotationPicture.split(",").map((i: string) => {
			return {
				url: i
			};
		});
		let arr = data.point.split(",");
		let [latt, lngg] = arr;
		lng.value = parseFloat(lngg);
		lat.value = parseFloat(latt);
	});
};
interface DrawerProps {
	title: string;
	isView: boolean;
	row: any | null;
	api?: (params: any) => Promise<any>;
	getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
	isView: false,
	title: "",
	row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
	drawerProps.value = params;
	drawerVisible.value = true;
};
// 选择城市
const handleCityClick = (val: string) => {
	ruleForm.value.city = val;
};
// 打开地图
const showMap = () => {
	nextTick(() => {
		bmapAddressSelect.value.show();
	});
};
// 获取地图信息
const confirmMapAddress = (addressInfo: any) => {
	let { latitude, longitude } = addressInfo[0];
	ruleForm.value.detailsAddress = addressInfo[1];
	ruleForm.value.point = `${latitude},${longitude}`;
	lng.value = longitude;
	lat.value = latitude;
};
//监听报名时间
watch(
	() => timeManagement.signTime,
	(date: Array<Date>) => {
		if (!date) return;
		ruleForm.value.signUpBeginTime = date[0];
		ruleForm.value.singUpEndTime = date[1];
	}
);
// 监听比赛时间
watch(
	() => timeManagement.gameTime,
	(date: Array<Date>) => {
		if (!date) return;
		ruleForm.value.matchBeginTime = date[0];
		ruleForm.value.matchEndTime = date[1];
	}
);
// 监听轮播图多图上传 给表单数据赋值
watch(
	() => ruleForm.value.fileList,
	() => {
		if (!ruleForm.value.fileList?.length) return;
		ruleForm.value.rotationPicture = (ruleForm.value.fileList as UploadUserFile[]).map(i => i.url).join(",");
	}
);
watch(
	() => drawerVisible.value,
	val => {
		if (!val) return;
		getDetailApi();
	}
);
// 限制比赛时间必须大于报名时间
const disablesDate = (time: any) => {
	if (!ruleForm.value.singUpEndTime) {
		return false;
	}
	const _minTime = new Date(ruleForm.value.singUpEndTime).getTime();
	return time.getTime() < _minTime;
};
// 限制报名时间必须大于当日时间
const pickerOptions = (time: any) => {
	const today = new Date();
	return time.getTime() < today.getTime() - 86400000;
};
//根据比赛类型得出金额
const handleChargeTypeChange = (val: number) => {
	if (val == 1) {
		ruleForm.value.money = 0;
	}
};
// 取消添加赛事
const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	ruleForm.value = {
		id: null,
		name: "",
		merchants: "",
		coverPicture: "",
		rotationPicture: "",
		fileList: [],
		city: "",
		address: "",
		detailsAddress: "",
		point: "",
		signUpBeginTime: "",
		singUpEndTime: "",
		matchBeginTime: "",
		matchEndTime: "",
		consultant: "",
		telePhone: "",
		state: 1,
		isEnable: 1,
		details: "",
		instructions: "",
		chargeType: 1,
		money: 0,
		officialOrBusiness: 0,
		hostUnit: [
			{
				name: "",
				logoUrl: "",
				responsible: "",
				telePohone: ""
			}
		],
		undertakeUnit: [
			{
				name: "",
				logoUrl: "",
				responsible: "",
				telePohone: ""
			}
		],
		assistingUnit: [
			{
				name: "",
				logoUrl: "",
				responsible: "",
				telePohone: ""
			}
		]
	};
	timeManagement.gameTime = [];
	timeManagement.signTime = [];
	drawerVisible.value = false;
};
// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = (n: number) => {
	ruleFormRef.value!.validate(async valid => {
		if (!valid) return;
		// 报名开始时间
		let signTiem = ruleForm.value.signUpBeginTime;
		// 比赛开始时间
		let gameStar = ruleForm.value.matchBeginTime;
		let bool = new Date(gameStar).getTime() > new Date(signTiem).getTime();
		if (!bool) {
			ElMessage.error("比赛时间一定要大于报名时间");
			return;
		}
		if (new Date(signTiem).getTime() < new Date().getTime() - 86400000) {
			ElMessage.error("比赛报名时间一定要大于当前时间");
			return;
		}
		try {
			if (n == 2) {
				ruleForm.value.isEnable = 1;
			}
			ruleForm.value.state = n;
			await competitionApi.EditCompetitionApi(ruleForm.value);
			ElMessage.success({ message: `${drawerProps.value.title}赛事成功！` });
			drawerProps.value.getTableList!();
			drawerVisible.value = false;
		} catch (error) {
			console.log(error);
		}
	});
};
getCompanyTypeList();
defineExpose({
	acceptParams
});
</script>
<style lang="scss" scoped>
.title {
	margin: 30px 0;
	span {
		position: relative;
		font-size: 22px;
		line-height: 22px;
		color: #000000;
		text-align: center;
		&::before {
			position: absolute;
			top: 0;
			left: -8px;
			width: 2px;
			height: 100%;
			content: "";
			background-color: #409eff;
		}
	}
}
.radioBox {
	display: flex;
	width: 100%;
}
</style>
